<template>
  <div style="padding: 10px">
      <el-row>
        <el-col :span="19">
          <div style="width: 800px; margin: 0 auto; background-color: #fcf3ec;
                    border-radius: 5px;border: 2px #000 solid">
            <div style="text-align: center; line-height: 50px;">聊天室<span v-show="chatUser">（{{ chatUser }}）</span></div>
            <div style="height: 400px; overflow:auto; border-top: 1px solid #ccc" v-html="content" />
            <div style="height: 50px;text-align: center">
              <div>
                <el-input style="display: inline-block;width: 400px" v-model="text"></el-input>
                <el-button style="margin-left: 5px" type="warning" @click="send">发送</el-button>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="5">
          <el-card style="height:400px;color: #333;background-color: #fcf3ec;border: 2px #000 solid" shadow="never">
            <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">在线用户<span style="font-size: 12px">（点击电话图标选择聊天对象）</span>
            </div>
            <div v-for="user in users" :key="user.username" style="padding: 10px 0">
              <span>{{ user.username }}</span>
              <i
                  class="el-icon-phone"
                  style="margin-left: 10px; font-size: 16px; cursor: pointer"
                  @click="chatUser = user.username"
              />
              <span v-if="user.username === chatUser" style="font-size: 12px;color: limegreen; margin-left: 5px">聊天中...</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
</template>

<script>
let socket

export default {
  name: 'Chat',
  data() {
    return {
      user: '',
      users: [],
      chatUser: '',
      text: '',
      content: ''
    }
  },
  computed: {
    username: function() {
      return this.$store.getters.username
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    send() {
      if (!this.chatUser) {
        this.$message({ type: 'warning', message: '请选择聊天对象', center: true })
        return
      }
      if (!this.text) {
        this.$message({ type: 'warning', message: '请输入内容', center: true })
      } else {
        if (typeof (WebSocket) === 'undefined') {
          console.log('您的浏览器不支持WebSocket')
        } else {
          console.log('您的浏览器支持WebSocket')
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          const message = { from: this.user, to: this.chatUser, text: this.text }
          socket.send(JSON.stringify(message)) // 将组装好的json发送给服务端，由服务端进行转发
          // 构建消息内容，本人消息
          this.createContent(null, this.user, this.text)
          this.text = ''
        }
      }
    },
    createContent(remoteUser, nowUser, text) { // 这个方法是用来将 json的聊天消息数据转换成 html的。
      let html
      // 当前用户消息
      if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息
        html = '<div class=\'right-content\'>\n' +
            '  <div style=\'padding-right: 10px\'>\n' +
            '    <div class=\'tip left-c\'>' + text + '</div>\n' +
            '  </div>\n' +
            '  <div >\n' +
            '  <span class=\'el-avatar el-avatar--circle\' style=\'height: 40px; width: 40px; line-height: 40px;\'>\n' +
            nowUser +
            '  </span>\n' +
            '  </div>\n' +
            '</div>'
      } else if (remoteUser) { // remoteUser表示远程用户聊天消息
        html = '<div class=\'left-content\'>\n' +
            '  <div>\n' +
            '  <span class=\'el-avatar el-avatar--circle\' style=\'height: 40px; width: 40px; line-height: 40px;\'>\n' +
            remoteUser +
            '  </span>\n' +
            '  </div>\n' +
            '  <div style=\'padding-left: 10px\' >\n' +
            '    <div class=\'tip right-c\'>' + text + '</div>\n' +
            '  </div>\n' +
            '</div>'
      }
      this.content += html
    },
    init() {
      this.user = this.username
      const username = this.username
      const _this = this
      if (typeof (WebSocket) === 'undefined') {
        console.log('您的浏览器不支持WebSocket')
      } else {
        console.log('您的浏览器支持WebSocket')
        const socketUrl = 'ws://localhost:8080/server/' + username
        if (socket != null) {
          socket.close()
          socket = null
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl)
        // 打开事件
        socket.onopen = function() {
          console.log('websocket已打开')
        }
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function(msg) {
          console.log('收到数据====' + msg.data)
          const data = JSON.parse(msg.data) // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
          if (data.users) { // 获取在线人员信息
            _this.users = data.users.filter(user => user.username !== username) // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
          } else {
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {"from": "zhang", "text": "hello"}
            // 构建消息内容
            _this.createContent(data.from, null, data.text)
            _this.chatUser = data.from
          }
        }
        // 关闭事件
        socket.onclose = function() {
          console.log('websocket已关闭')
        }
        // 发生了错误事件
        socket.onerror = function() {
          console.log('websocket发生了错误')
        }
      }
    }

  }
}

</script>

<style>
.tip {
  color: white;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width: auto;
}

.right-content {
  display: -webkit-flex;
  display: flex;
  justify-content: flex-end;
  padding: 5px 5px
}

.left-content {
  display: -webkit-flex;
  display: flex;
  justify-content: flex-start;
  padding: 5px 5px
}

.right-c {
  background-color: #ebb563;
}

.left-c {
  background-color: #4d4552;
}
</style>
